package org.phalanx.server.game;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

import org.phalanx.map.MapCoordinates;
import org.phalanx.server.ServerCache.Cacheable;

public class GameState implements Cacheable {
	private Integer gameId;
	private ArrayList<PhalanxUnitState> unitStateList;
	
	public GameState(Integer turnId){
		setId(turnId);
		unitStateList = new ArrayList<PhalanxUnitState>();
	}
	
	public ArrayList<PhalanxUnitState> getUnitStates(){
		return unitStateList;
	}
	
	public void addUnitState(PhalanxUnitState uState){
		if (!unitStateList.contains(uState)){
			unitStateList.add(uState);
		}
	}
	
	public void removeUnitState(PhalanxUnitState uState){
		if (unitStateList.contains(uState)){
			unitStateList.remove(uState);
		}
	}
	
	public ArrayList<PhalanxUnitState> getUnitStateForCurrentTurn(Integer turnId){
		ArrayList<PhalanxUnitState> unitStateForTurn = new ArrayList<PhalanxUnitState>();
		
		Iterator<PhalanxUnitState> i = this.getUnitStates().iterator();
		
		while(i.hasNext()){
			PhalanxUnitState uState = i.next();
			
			if (uState.getTurnId().equals(turnId)){
				unitStateForTurn.add(uState);
			}
		}
		
		return unitStateForTurn;
	}
	
	public ArrayList<Integer> getUnitAt(MapCoordinates c, Integer turnId){
		ArrayList<Integer> unitIds = new ArrayList<Integer>();
		
		Iterator<PhalanxUnitState> i = getUnitStateForCurrentTurn(turnId).iterator();
		
		while (i.hasNext()){
			PhalanxUnitState oneUnit = i.next();
			
			if (oneUnit.getMapCoordinates().equals(c)){
				unitIds.add(oneUnit.getUnitId());
			}
		}
		
		return unitIds;
	}
	
	public PhalanxUnitState getUnitTypeById(Integer unitId, Integer turnId){
		PhalanxUnitState unitType = null;
		
		Iterator<PhalanxUnitState> i = getUnitStateForCurrentTurn(turnId).iterator();
		boolean isFound = false;
		
		while (i.hasNext() && !isFound){
			PhalanxUnitState oneState = i.next();
			
			if (oneState.getUnitId().equals(unitId)){
				unitType = oneState;
			}
		}
		
		return unitType;
	}
	
	public Integer generateUnitStateId(Integer turn){
		Integer newUnitId = -1;
		
		Random r = new Random(new Date().getTime());
		
		do {
			newUnitId = Math.abs(r.nextInt() % 1000000); 
		} while (this.getUnitTypeById(newUnitId, turn) != null); // Check if unique
		
		return newUnitId;
	}
	
	@Override
	public Integer getId() {
		// TODO Auto-generated method stub
		return gameId;
	}

	@Override
	public void setId(Integer id) {
		this.gameId = id;
	}

}
